import dayjs from "dayjs";
import { ref, onMounted, h } from "vue";
import { usePublicHooks } from "../hooks";
import { cloneDeep, isAllEmpty } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "../utils/types";
import elForm from '../form.vue'

import { getMenuTreeList, addMenu, updateMenu, deleteMenu } from "@/utils/api/system/menu";

export function useDept() {
  const formRef = ref();
  const dataList: any = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "Name",
      width: 200,
      align: "left"
    },
    {
      label: "菜单编码",
      prop: "Code",
      minWidth: 130
    },
    {
      label: "菜单请求地址",
      prop: "pageurl",
      minWidth: 130
    },
    {
      label: "前端组件/API地址",
      prop: "apiurl",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.Status)}>
          {row.Status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "类型",
      prop: "type",
      minWidth: 70,
      formatter: (row) => {
        let data: string = '';
        switch (row.type) {
          case 1:
            data = '系统'
            break;
          case 2:
            data = '目录'
            break;
          case 3:
            data = '页面'
            break;
          case 4:
            data = '功能'
            break;
          default:
            data = '--'
        }
        return data
      }
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "CreateTime",
      formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function formatOptions(treeList) {
    const menu = [{ Id: 1, Name: '主类目', children: [] }];
    menu[0].children = treeList
    return menu;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          higherDeptOptions: formatOptions(cloneDeep(dataList.value)),
          parentId: row?.ParentId ?? 0,
          name: row?.Name ?? "",
          pageUrl: row?.pageurl ?? "",
          code: row?.Code ?? "",
          apiUrl: row?.apiurl ?? "",
          icon: row?.icon ?? "",
          sort: row?.Sort ?? null,
          status: row?.Status ?? 1,
          type: row?.type ?? 1
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(elForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了菜单名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
                //@ts-ignore
              addMenu(curData).then(res => {
                if (res.Code === 0) chores();
              })
            } else {
              let data = Object.assign(curData, { Id: row.Id })
              //@ts-ignore
              updateMenu(data).then(res => {
                if (res.Code === 0) chores();
              })
            }
          }
        });
      }
    })
  }

  async function onSearch() {
    loading.value = true;
    const { Content } = await getMenuTreeList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    let newData = Content;
    processData(newData)
    dataList.value = newData; // 处理成树结构
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 过滤树形数据
  function processData(arr: { [key: string]: any; }) {
    for (let i = 0; i < arr.length; i++) {
      arr[i].children = arr[i].Children
      if (Array.isArray(arr[i].Children)) {
        processData(arr[i].Children)
      }
    }
  }

  // 删除
  function handleDelete(row) {    
    ElMessageBox.confirm(
      `是否确认删除名称为${row.name}的数据项?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      deleteMenu(row.Id).then(res => {
        if (res.Code === 0) {
          message(`您删除了菜单名称为${row.Name}的这条数据`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  onMounted(() => {
    onSearch()
  })

  return {
    dataList,
    loading,
    columns,
    onSearch,
    openDialog,
    handleDelete
  };
}
